#include "middle.h"
#include "ui_middle.h"
#include "SQL/sql.h"
#include <QDebug>

Middle::Middle(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Middle)
{
    ui->setupUi(this);

    ui->username->setPlaceholderText("账号");
    ui->password->setPlaceholderText("密码");
    ui->password->setEchoMode(QLineEdit::Password);

    connect(ui->btnLogin, &QPushButton::clicked, this, &Middle::onLogin);
    connect(ui->btnEnroll, &QPushButton::clicked, this, [=](){
        emit Enroll(INDEX_ENROLL);
    });
    connect(ui->btnForget, &QPushButton::clicked, this, [=](){
        emit Forget(INDEX_FORGET);
    });

}

Middle::~Middle()
{
    delete ui;
}

void Middle::onLogin()
{
    UserDatabase user;
    QString name = ui->username->text();
    QString password = ui->password->text();
    if (ui->username->text().isEmpty() || ui->password->text().isEmpty()) {
        qDebug() << "不能为空";
        return;
    }
    if(!user.openDatabase("users.db")){
        return;
    }
    if(user.authenticateUser(name,password)){
        emit LoginSucceed(INDEX_ADMINWINDOW);
    }else{
        emit LoginFail();
    }
    ui->username->clear();
    ui->password->clear();
    user.closeDatabase();
}


